import {
  getSetting,
  openSetting,
  chooseAddress,
  showModal,
  showToast
} from "../../utils/asyncWx.js";
import regeneratorRuntime from "../../lib/runtime/runtime";

Page({
  data: {
    address: {},
    cartGoods: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },
  async handleChooseAddress() {
    try {
      const res1 = await getSetting();
      const res = res1.authSetting["scope.address"];
      if (res === false) {
        await openSetting();
      }
      const res2 = await chooseAddress();
      wx.setStorageSync("address", res2);
    } catch (err) {
      console.log(err);
    }
  },
  onShow() {
    const address = wx.getStorageSync("address") || {};
    console.log(address);
    address.address =
      address.provinceName +
      address.cityName +
      address.countryName +
      address.detailInfo;
    const goods = wx.getStorageSync("cart") || [];
    this.setData({
      address
    });
    this.setCart(goods);
  },
  onLoad() {},
  handleChange(e) {
    const id = e.currentTarget.dataset.id;
    console.log(id);
    const cartGoods = this.data.cartGoods;
    const index = cartGoods.findIndex(v => v.goods_id === id);
    cartGoods[index].check = !cartGoods[index].check;
    this.setCart(cartGoods);
  },
  handleAllChange() {
    const allChecked = !this.data.allChecked;
    const { cartGoods } = this.data;
    cartGoods.forEach(v => {
      v.check = allChecked;
    });
    this.setCart(cartGoods);
  },

  async handleNumChange(e) {
    const { id, operation } = e.currentTarget.dataset;
    console.log(id, operation);
    const { cartGoods } = this.data;
    const index = cartGoods.findIndex(v => v.goods_id === id);
    let num = cartGoods[index].num;
    if (num === 1 && operation == -1) {
      const res = await showModal("你确定要要把此产品从购物车中移除吗? ");
      if (res.confirm) {
        cartGoods.splice(index, 1);
        this.setCart(cartGoods);
      } else {
        console.log("用户点击取消");
      }
    } else {
      cartGoods[index].num += operation - 0;
      this.setCart(cartGoods);
    }
  },
  setCart(cart) {
    let allChecked = true;
    let totalNum = 0;
    let totalPrice = 0;
    cart.forEach(v => {
      if (v.check) {
        totalPrice += v.goods_price * v.num;
        totalNum += v.num;
      } else {
        allChecked = false;
      }
    });
    allChecked = cart.length === 0 ? false : allChecked;
    this.setData({
      cartGoods: cart,
      allChecked: allChecked,
      totalNum,
      totalPrice
    });
    wx.setStorageSync("cart", cart);
  },
  async handlePay() {
    if (this.data.address.length === 0) {
      const res = await showToast("请先填写地址");
      return;
    }
    if (this.data.totalNum == 0) {
      const res = await showToast("请先选择商品");
      return;
    }
    wx.navigateTo({
      url: "/pages/pay/index"
    });
  }
});
